<script setup lang="ts">
// /api/admin/profits/users/stats
import { useDark, useECharts } from "@pureadmin/utils";
import { ref, watch, nextTick, PropType } from "vue";
import { generatePalette } from "@/plugins/echarts";

// TS 类型定义
interface UserStatsItem {
  username: string;
  totalProfit: number;
  totalSales: number;
  totalTasks: number;
  totalCost: number;
  timeStats?: Array<{
    period: string;
    cost: number;
    profit: number;
    sales: number;
    tasks: number;
  }>;
}

const props = defineProps({
  // 传入的 data 就是一个数组，数组中的对象包含用户统计数据
  data: {
    type: Array as PropType<Array<UserStatsItem>>,
    default: () => []
  }
});

const chartRef = ref<HTMLDivElement>();
const { isDark } = useDark();
const themeName = "lowSaturationFancy";
const { setOptions } = useECharts(chartRef, { theme: themeName });

watch(
  () => props.data,
  async (list: UserStatsItem[]) => {
    await nextTick();

    // X 轴：用户名
    const categories = list.map(item => item.username);
    // 系列数据
    const profitData = list.map(item => item.totalProfit);
    const salesData = list.map(item => item.totalSales);
    const tasksData = list.map(item => item.totalTasks);
    const costData = list.map(item => item.totalCost);

    // 动态配色
    const seriesCount = 4;
    const colors = generatePalette(seriesCount);

    setOptions({
      color: colors,
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" }
      },
      grid: {
        top: "20px",
        left: "0px",
        right: "0px",
        bottom: "0px",
        containLabel: true
      },
      legend: {
        data: ["总利润", "总销售额", "总任务数", "总成本"],
        textStyle: { color: isDark.value ? "#fff" : "#666", fontSize: 12 },
      },
      xAxis: [
        {
          type: "category",
          data: categories,
          axisLabel: { fontSize: 12, color: isDark.value ? "#fff" : "#666" },
          axisPointer: { type: "shadow" }
        }
      ],
      yAxis: [
        {
          type: "value",
          axisLabel: { fontSize: 12, color: isDark.value ? "#fff" : "#666" },
          splitLine: { show: false }
        }
      ],
      series: [
        {
          name: "总利润",
          type: "bar",
          barWidth: 12,
          itemStyle: { borderRadius: [4, 4, 0, 0] },
          data: profitData
        },
        {
          name: "总销售额",
          type: "bar",
          barWidth: 12,
          itemStyle: { borderRadius: [4, 4, 0, 0] },
          data: salesData
        },
        {
          name: "总任务数",
          type: "bar",
          barWidth: 12,
          itemStyle: { borderRadius: [4, 4, 0, 0] },
          data: tasksData
        },
        {
          name: "总成本",
          type: "bar",
          barWidth: 12,
          itemStyle: { borderRadius: [4, 4, 0, 0] },
          data: costData
        }
      ]
    });
  },
  { immediate: true, deep: true }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 365px" />
</template>
